﻿using System;
using System.Diagnostics;
using Soundteller.Audio.Model;
using Soundteller.Audio.Repositories.Interfaces;
using Soundteller.Audio.Services.Interfaces;

namespace Soundteller.Audio.Services
{
    public class SongLoader : ISongLoader
    {
        private readonly IStorageRepository _storageRepository;
        private readonly ISongRepository _songRepository;

        public SongLoader(IStorageRepository storageRepository, ISongRepository songRepository)
        {
            if (storageRepository == null) throw new ArgumentNullException("storageRepository");
            if (songRepository == null) throw new ArgumentNullException("songRepository");

            _storageRepository = storageRepository;
            _songRepository = songRepository;
        }

        public void LoadByFilePath(string filePath)
        {
            Debug.WriteLine("{0}.LoadBySong( {1} )", GetType().Namespace, filePath);

            var song = _storageRepository.Load<Song>(filePath);
            if (song == null)
                throw new InvalidOperationException("Song not found in specified file path");

            if(_songRepository.GetById(song.Id) != null)
                _songRepository.DeleteById(song.Id);

            _songRepository.Add(song);
            _songRepository.UpdateActiveSong(song);
        }
    }
}